<template>
    <div id="bottomImg" class="bottomImg"
        :style="{ height: imgHeigth, width: imgWidth, backgroundImage: 'url(' + props.bottomImg + ')' }">
        <span class="imgLabel">{{ props.bottomLabel }}</span>
        <div v-if="props.upperImg" class="upperImg"
            :style="{ backgroundImage: 'url(' + props.upperImg + ')', width: 100 - upperImgWidth + '%' }">
            <span class="imgLabel">{{ props.upperLabel }}</span>
        </div>
        <div v-else class="upperUndefined" :style="{ width: 100 - upperImgWidth + '%' }">
            <span class="undefinedSpan">暂无结果</span>
        </div>
        <span class="spanHandle" :style="{ left: 'calc(' + upperImgWidth + '% - 24px)' }"></span>
        <input class="inputRange" type="range" v-model="upperImgWidth" min="0" max="100" />
    </div>
</template>
<script lang="ts" setup>
import "@/assets/twoImgCompare.scss";
const imgHeigth = ref("0px");
const imgWidth = ref("0px");
const upperImgWidth = ref(50);
const props = defineProps({
    bottomImg: {
        type: String,
        default: "",
    },
    upperImg: {
        type: String,
        default: "",
    },
    bottomLabel: {
        type: String,
        default: "原图",
    },
    upperLabel: {
        type: String,
        default: "结果图",
    },
});
// 跟踪底层图片的变化，因为底层图片是基础
watch(
    () => props.bottomImg,
    () => {
        getImgSize();
        upperImgWidth.value = 50;
    }
);
let maxWidth = 0;
let maxHeight = 0;
// 首次加载时初始化
onMounted(() => {
    maxWidth = (document.documentElement.clientWidth - leftMenuWidth().value) * 0.9; // 减去左侧菜单的宽度，减去一定的空间预留
    maxHeight = document.documentElement.clientHeight * 0.8; // 减去一定的空间预留，防止图片过大时，页面被图片撑开。
    getImgSize();
});
function getImgSize() {
    //加载图片获取图片真实宽度和高度
    var image = new Image();
    image.onload = function () {
        // 防止图片太小影响观感，图片高度小于300px放大到300px
        let fangDaXiShu = 1;
        if (image.height < 100) {
            fangDaXiShu = 100 / image.height;
        }
        let newImgWidth = image.width * fangDaXiShu;
        let newImgHeight = image.height * fangDaXiShu;
        let kuangDubi = Math.min(maxWidth / newImgWidth, 1);
        let gaoDubi = Math.min(maxHeight / newImgHeight, 1);


        if (kuangDubi <= gaoDubi) {
            imgWidth.value = newImgWidth * kuangDubi + "px"; //限制宽度为最大宽度。
            imgHeigth.value = newImgHeight * kuangDubi + "px"; //高度按宽高比缩放。
        } else {
            imgHeigth.value = newImgHeight * gaoDubi + "px"; //限制高度为最大高度。
            imgWidth.value = newImgWidth * gaoDubi + "px"; //宽度按宽高比缩放。
        }
    };
    image.src = props.bottomImg; //img.src 应该是放在 onload 方法后边的, 因为当image的src发生改变，浏览器就会跑去加载这个src里的资源,先告诉浏览器图片加载完要怎么处理，再让它去加载图片
}
</script>
